package com.hankol.material

import android.graphics.Rect
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.activity.BaseFragment
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.bean.download.ShowUIUtils
import com.baselibrary.db.DBManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.GlideUtils
import com.baselibrary.utils.SpUtils
import com.google.android.material.tabs.TabLayout
import com.hankol.material.adapter.HomePagerAdapter
import com.hankol.material.api.OnTouchOutsideViewListener
import com.hankol.material.bean.HotPopupData
import com.hankol.material.databinding.ActivityMaterialMainHomeBinding
import com.hankol.material.fragment.HomeFolderFragment
import com.hankol.material.fragment.TabMaterialFragment
import com.hankol.material.viewmodel.MaterialMainHomeViewModel
import com.okhttp.SendRequest
import com.okhttp.callbacks.GenericsCallback
import com.okhttp.sample_okhttp.JsonGenericsSerializator
import okhttp3.Call
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**新版素材库首页
 * @author: merbng
 * @time: 2021/10/15 10:02
 * @description:
 */
@Route(path = ActivityRouter.MATERIAL.HOME_PAGE)
class MaterialMainHomeActivity : BaseActivity() {
    private lateinit var viewModel: MaterialMainHomeViewModel
    private lateinit var binding: ActivityMaterialMainHomeBinding
    private var mTouchOutsideView: View? = null
    private var mOnTouchOutsideViewListener: OnTouchOutsideViewListener? = null


    override fun getLayoutId(): Int {
        return R.layout.activity_material_main_home
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        setStatusBarDarkTheme(false)
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(MaterialMainHomeViewModel::class.java)
        binding.backImageView.setOnClickListener { finish() }

        binding.imgDownload.setOnClickListener {
            //进入下载页面
            ActivityRouter.startActivity(ActivityRouter.MATERIAL.MATERIAL_DOWNLOAD_MAIN)
        }
        binding.tvSearch.setOnClickListener { ActivityRouter.startActivity(ActivityRouter.MATERIAL.SEARCH) }

        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                binding.titleRl.visibility = if (tab.position == 1) View.GONE else View.VISIBLE
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
            }

            override fun onTabReselected(tab: TabLayout.Tab) {

            }
        })

        val listData = ArrayList<String>()
        listData.add("素材库")
        listData.add("收藏夹")
        val mAdapter = HomePagerAdapter(supportFragmentManager)
        val fragmentList = mutableListOf<BaseFragment>()
        fragmentList.add(TabMaterialFragment.newInstance())
        fragmentList.add(HomeFolderFragment.newInstance())
        mAdapter.fragments = fragmentList
        binding.viewPager.adapter = mAdapter
        binding.viewPager.offscreenPageLimit = listData.size
        binding.tabLayout.setupWithViewPager(binding.viewPager)
        mAdapter.setData(listData)
        SensorsDataManager.instance.memberPageElementClick("素材库")
    }

    override fun onResume() {
        super.onResume()
        showDownloadStatus()
        requestConfig()
    }

    val userIds: Int by lazy { SpUtils.getInstance().userId }

    //显示 下载中的动图 或者 静态图
    private fun showDownloadStatus() {
        val downloadList = mutableListOf<DownloadInfo>()
        try {
            downloadList.addAll(DBManager.getInstance().getDownloadList(userIds, true))
        } catch (e: Exception) {
        }
        val list = mutableListOf<DownloadInfo>()
        for (info in downloadList) {
            if ((info.downloadStatus.equals(DownloadInfo.DOWNLOAD) || info.downloadStatus.equals(DownloadInfo.DOWNLOAD_PAUSE) || info.downloadStatus.equals(DownloadInfo.DOWNLOAD_WAIT)))
                list.add(info)
        }
        if (list.size > 0) {
            binding.tvDownloadRedCnt.visibility = View.VISIBLE
            binding.tvDownloadRedCnt.text = "${ShowUIUtils.showFormatCnt(list.size)}"
            GlideUtils.loadGif(this, R.drawable.ic_top_downloading, binding.imgDownload)
        } else {
            binding.tvDownloadRedCnt.visibility = View.GONE
            GlideUtils.loadImg(this, R.drawable.ic_top_download, binding.imgDownload)
        }
    }

    fun setOnTouchOutsideViewListener(view: View, onTouchOutsideViewListener: OnTouchOutsideViewListener) {
        mTouchOutsideView = view
        mOnTouchOutsideViewListener = onTouchOutsideViewListener
    }

    fun getOnTouchOutsideViewListener(): OnTouchOutsideViewListener? {
        return mOnTouchOutsideViewListener
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            if (mOnTouchOutsideViewListener != null && mTouchOutsideView != null
                    && mTouchOutsideView?.visibility == View.VISIBLE) {
                val viewRect = Rect()
                mTouchOutsideView?.getGlobalVisibleRect(viewRect)
                if (!viewRect.contains(ev.rawX.toInt(), ev.rawY.toInt())) {
                    mOnTouchOutsideViewListener?.onTouchOutside(mTouchOutsideView, ev)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())) {
            showDownloadStatus()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgid_start_download || messageBus.codeType == MessageBus.msgId_del_material_file) {//下载完成或者删除下载的文件
            showDownloadStatus()
        }
    }

    override fun onBackPressed() {
        if (binding.tabLayout.getSelectedTabPosition() == 0) {
            finish()
        } else {
            binding.viewPager.currentItem = 0
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
    //素材库文档下载权限
    private fun requestConfig() {
        SendRequest.getHotPopup(Constants.token, object : GenericsCallback<HotPopupData>(
            JsonGenericsSerializator()
        ) {
            override fun onError(call: Call, e: Exception, id: Int) {}

            override fun onResponse(response: HotPopupData?, id: Int) {
                if (response == null || response!!.getData() == null || response!!.getData().getConfig_web_activity20210101() == null)
                    return
                val canDown = response!!.getData().getConfig_web_fileLib_canDown()
                if (canDown != null && !TextUtils.isEmpty(canDown)) {//素材库文档下载:0-不允许，1-允许
                    // false：不允许
                    SpUtils.getInstance().putMaterialDocumentDownPermision(canDown == "1")
                } else {//默认不允许
                    SpUtils.getInstance().putMaterialDocumentDownPermision(false)
                }
            }
        })
    }
}